//
//  ImagePickerManager.m
//  PickerManager
//
//  Created by iOS开发 on 2018/8/15.
//  Copyright © 2018年 iOS开发. All rights reserved.
//

#import "ImagePickerManager.h"
#import "TZImagePickerController.h"
#import <MobileCoreServices/MobileCoreServices.h>

@interface ImagePickerManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property(nonatomic,strong) UIImagePickerController *picker;
@end

@implementation ImagePickerManager

- (void)dealloc {
    NSLog(@"释放%@", NSStringFromClass([self class]));
}

- (NSMutableArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = @[].mutableCopy;
    }
    return _selectedAssets;
}
- (NSInteger)maxCount {
    if (!_maxCount) {
        _maxCount = 9;
    }
    return _maxCount;
}

- (UIImagePickerController *)picker {
    if (!_picker) {
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate =self;
    }
    return _picker;
}

#pragma mark - api
- (void)pushPickerFromVC:(UIViewController *)vc block:(PickerBlock)block {
    if (_isShowSheet) {
        [self showAlertWithVC:vc block:block];
    } else {
        [self presentAlbumtWithVC:vc block:block];
    }
}

- (void)showAlertWithVC:(UIViewController *)vc block:(PickerBlock)block {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhotoWithVC:vc];
    }];
    [alertVc addAction:takePhotoAction];
    UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self presentAlbumtWithVC:vc block:block];
    }];
    [alertVc addAction:imagePickerAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:cancelAction];
    [vc presentViewController:alertVc animated:YES completion:nil];
}

// 拍照
- (void)takePhotoWithVC:(UIViewController *)vc {
    
    // 如果拍摄的摄像头可用
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        // 将sourceType设为UIImagePickerControllerSourceTypeCamera代表拍照或拍视频
        self.picker.sourceType =UIImagePickerControllerSourceTypeCamera;
        // 设置拍摄照片
        self.picker.cameraCaptureMode =UIImagePickerControllerCameraCaptureModePhoto;
        // 设置使用手机的后置摄像头（默认使用后置摄像头）
        self.picker.cameraDevice =UIImagePickerControllerCameraDeviceRear;
        // 设置使用手机的前置摄像头。
        //picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        // 设置拍摄的照片允许编辑
//        self.picker.allowsEditing =YES;
    }else{
        NSLog(@"模拟器无法打开摄像头");
    }
    [vc presentViewController:self.picker animated:YES completion:nil];
}

// 当得到照片或者视频后，调用该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    // 获取用户拍摄的是照片还是视频
    NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    // 判断获取类型：图片，并且是刚拍摄的照片
    if ([mediaType isEqualToString:(NSString*)kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        UIImage *theImage = nil;
        // 判断，图片是否允许修改
        if ([picker allowsEditing]) {
            // 获取用户编辑之后的图像
            theImage = [info objectForKey:UIImagePickerControllerEditedImage];
        }else {
            // 获取原始的照片
            theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        // 保存图片到相册中
        NSMutableArray *imageIds = [NSMutableArray array];
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:theImage];
            //记录本地标识，等待完成后取到相册中的图片对象
            [imageIds addObject:req.placeholderForCreatedAsset.localIdentifier];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                //成功后取相册中的图片对象
                __block PHAsset *imageAsset = nil;
                PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:imageIds options:nil];
                [result enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    imageAsset = obj;
                    *stop = YES;
                }];
                if (imageAsset) {
                    //加载图片数据
                    [self.selectedAssets addObject:imageAsset];
                }
            }
        }];
        
        // 图片回调
        if (self.cameraBlock) {
            self.cameraBlock(theImage);
        }
    }
    // 隐藏UIImagePickerController
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 去相册
- (void)presentAlbumtWithVC:(UIViewController *)vc block:(PickerBlock)block {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxCount delegate:nil];
    // 不支持图片 不支持gif
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingVideo = NO;
     // 目前已经选中的图片数组
    imagePickerVc.selectedAssets = self.selectedAssets;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [self.selectedAssets removeAllObjects];
        [self.selectedAssets addObjectsFromArray:assets];
        block(photos);
    }];
    [vc presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)deleteSelectPhoto:(NSInteger)index {
    [self.selectedAssets removeObjectAtIndex:index];
}

@end
